using AutoMapper;
using BackData;
using Domain;
using Domain.DTOs.BOMs;
using Infratructure;
using MediatR;
using Team.API.Applocation.Command.BOM;

namespace Team.API.Applocation.Hanldler.BOM
{
    /// <summary>
    /// 获取BOM操作日志列表处理器
    /// </summary>
    public class GetBOMLogsHandler : IRequestHandler<GetBOMLogsCommand, APIPaging<BOMLogDTO>>
    {
        private readonly IRepository<Nlogmodel> nlogRepository;
        private readonly IMapper mapper;
        private readonly ILogger<GetBOMLogsHandler> logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="nlogRepository">日志仓储</param>
        /// <param name="mapper">对象映射器</param>
        /// <param name="logger">日志记录器</param>
        public GetBOMLogsHandler(
            IRepository<Nlogmodel> nlogRepository,
            IMapper mapper,
            ILogger<GetBOMLogsHandler> logger)
        {
            this.nlogRepository = nlogRepository;
            this.mapper = mapper;
            this.logger = logger;
        }

        /// <summary>
        /// 处理获取BOM操作日志列表请求
        /// 筛选条件：Category == "BOM" && IsDel == false
        /// </summary>
        /// <param name="request">查询命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>分页结果</returns>
        public Task<APIPaging<BOMLogDTO>> Handle(GetBOMLogsCommand request, CancellationToken cancellationToken)
        {
            var result = new APIPaging<BOMLogDTO>();

            try
            {
                // 基础查询：筛选BOM类别且未删除的记录（不依赖外键参数）
                var query = nlogRepository.GetAll()
                    .Where(x => x.Category == "BOM" && x.IsDel == false);

                // 搜索关键词筛选（搜索操作内容或操作人）
                if (!string.IsNullOrWhiteSpace(request.SearchKeyword))
                {
                    var keyword = request.SearchKeyword.Trim();
                    query = query.Where(x =>
                        (x.Message != null && x.Message.Contains(keyword)) 
                        //||
                        //(x.Createname != null && x.Createname.Contains(keyword))
                    );
                }

                // 获取总数
                var totalCount = query.Count();

                if (totalCount > 0)
                {
                    // 分页查询，按创建时间倒序排列（最新的在前）
                    var list = query
                        //.OrderByDescending(x => x.Createtime)
                        .Skip((request.Pageindex - 1) * request.Pagesize)
                        .Take(request.Pagesize)
                        .ToList();

                    // 映射到DTO
                    var dtoList = mapper.Map<List<BOMLogDTO>>(list);

                    result.Totalcount = totalCount;
                    result.Code = StateCode.OK;
                    result.Message = "BOM操作日志列表获取成功";
                    result.ListResult = dtoList;
                }
                else
                {
                    result.Totalcount = 0;
                    result.Code = StateCode.OK;
                    result.Message = "未找到符合条件的操作记录";
                    result.ListResult = new List<BOMLogDTO>();
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取BOM操作日志列表时发生错误");
                result.Code = StateCode.Fail;
                result.Message = "BOM操作日志列表获取失败：" + ex.Message;
                result.ListResult = new List<BOMLogDTO>();
            }

            return Task.FromResult(result);
        }
    }
}

